/**
 * @(#)ExpressService.java, 2013-2-14. Copyright 2013 RENREN, Inc. All rights
 *                          reserved. RENREN PROPRIETARY/CONFIDENTIAL. Use is
 *                          subject to license terms.
 */
package com.wennimei.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wennimei.util.HttpUtil;

/**
 * @author shichen.feng@renren-inc.com
 */
@Service
public class ExpressService {

    private static final Map<String, String> nameref = new HashMap<String, String>();

    @PostConstruct
    void init() {
        nameref.put("申通", "shentong");
        nameref.put("中通", "zhongtong");
        nameref.put("韵达", "yunda");
        nameref.put("宅急送", "zhaijisong");
        nameref.put("圆通", "yuantong");
        nameref.put("汇通", "huitongkuaidi");
        nameref.put("天天", "tiantian");
        nameref.put("全峰", "quanfengkuaidi");
        nameref.put("凡客", "rufengda");
        nameref.put("如风达", "rufengda");
        nameref.put("联邦", "lianbangkuaidi");
        nameref.put("dhl", "dhl");
        nameref.put("德邦", "debangwuliu");
        nameref.put("尚橙", "shangcheng");
        nameref.put("新蛋", "neweggozzo");
    }

    @SuppressWarnings("unchecked")
    public String get(String content) {
        String url = "http://baidu.kuaidi100.com/query?type=%s&postid=%s";
        String code = content.replaceAll("[^0-9]", "");
        String type = content.replace(code, "").toLowerCase();
        String expressName = null;
        for (String s: nameref.keySet()) {
            if (type.contains(s)) {
                type = nameref.get(s);
                expressName = s;
                break;
            }
        }
        url = String.format(url, type, code);
        String json = HttpUtil.get(url);
        Gson gson = new Gson();
        Map<String, Object> res = gson.fromJson(json,
                new TypeToken<Map<String, Object>>() {}.getType());
        List<Map<String, String>> list = (List<Map<String, String>>) res
                .get("data");

        if (null == list || list.size() == 0)
            return "对不起，暂未查到此运单流转信息，可能是服务商暂未录入到系统中，请稍后再试";

        StringBuilder sb = new StringBuilder();
        sb.append(expressName + "," + code + "(只显示最近10条记录)\r\n");
        if (list.size() > 10)
            list = list.subList(0, 10);
        for (Map<String, String> m: list) {
            sb.append(m.get("time") + "\r\n").append(m.get("context") + "\r\n");
        }
        return sb.toString();
    }

    public static boolean isExpress(String content) {
        for (String s: nameref.keySet()) {
            if (content.contains(s))
                return true;
        }
        return false;
    }
}
